<script setup lang="ts">
import UQRCode from 'uqrcodejs';
import { computed, getCurrentInstance, nextTick, ref, watch } from 'vue';

const props = withDefaults(
  defineProps<{
    margin?: number
    size?: number
    content: string | number
  }>(),
  { size: 200, margin: 10 }
);

const instance = getCurrentInstance();

const style = computed(() => {
  const size = `${props.size}px`;
  return { width: size, height: size };
});

const canvasImg = ref('');

async function createQrCode() {
  if (!props.content) {
    return;
  }

  try {
    await nextTick();
    const size = props.size;

    // 获取uQRCode实例
    const qr = new UQRCode();
    qr.setOptions({
      data: props.content,
      size,
      margin: props.margin
    });

    // 调用制作二维码方法
    qr.make();

    // 获取canvas上下文
    const canvasContext = uni.createCanvasContext('qrcode', instance?.proxy);
    if (!canvasContext) {
      throw new Error('无法获取canvas上下文');
    }

    // 设置uQRCode实例的canvas上下文
    qr.canvasContext = canvasContext;

    // 绘制图形
    await qr.draw();

    console.log('二维码绘制完成，开始转换为图片');

    // 转换为图片
    return new Promise((resolve, reject) => {
      uni.canvasToTempFilePath(
        {
          width: size,
          height: size,
          destWidth: size,
          destHeight: size,
          canvasId: 'qrcode',
          success(res) {
            console.log('二维码转换成功:', res);
            canvasImg.value = res.tempFilePath;
            resolve(res.tempFilePath);
          },
          fail(err) {
            console.error('二维码转换失败:', err);
            reject(err);
          }
        },
        instance?.proxy
      );
    });
  }
  catch (error) {
    console.error('二维码生成失败:', error);
    throw error;
  }
}

function watchContent() {
  if (props.content) {
    createQrCode();
  }
}

watch(() => props.content, watchContent, { immediate: true });

defineExpose({
  createQrCode
});
</script>

<template>
  <view class="canvas-part" :style="style">
    <image v-if="canvasImg" class="canvas-img" :src="canvasImg" />
    <view v-else-if="!canvasImg" class="loading-placeholder">
      <text class="loading-text">
        二维码生成中...
      </text>
    </view>
    <canvas id="qrcode" class="canvas-code" canvas-id="qrcode" :style="style" />
  </view>
</template>

<style scoped lang="scss">
.canvas-part {
  width: 200px;
  height: 200px;
  margin: 0 auto;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e0e0e0;

  .canvas-img {
    width: 100%;
    height: 100%;
    border-radius: 8px;
  }

  .loading-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }

  .loading-text {
    font-size: 24px;
    color: #999;
  }

  .canvas-code {
    position: absolute;
    left: -9999px; // 隐藏canvas但保持在DOM中
    top: 0;
  }
}
</style>
